/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.comut.crud.bo;

import com.comut.crud.dao.UserDao;
import com.comut.crud.ejb.interfaces.IUserAction;
import com.comut.crud.pojo.FindAndSet;
import com.comut.crud.pojo.user.User;
import com.comut.crud.util.ParseJson;
import com.comut.lib.error.ErrorCodes;
import com.comut.lib.exception.JSONMalFormedException;
import com.comut.lib.exception.ObjectFoundException;
import com.comut.lib.exception.ObjectNotFoundException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ResourceBundle;
import java.util.logging.Level;
import org.apache.log4j.Logger;

/**
 *
 * @author asantos
 */
public class UserHandler implements IUserAction {

    private static Logger _logger = Logger.getLogger(UserHandler.class.getName());
    private static final String _tagsSeparator = ResourceBundle.getBundle("application").getString("tagsSeparator");
    private Connection _connection;
    private UserDao userDao;

    public UserHandler(Connection connection) {
        this._connection = connection;
        userDao = new UserDao(_connection);

    }

    public User insertUser(User user) throws ObjectFoundException {
        if (user.isValid()) {
            int id = userDao.createUser(user);
            User toRet = new User();
            toRet.setId(id);
            String tags = getUserTags(id);
            user.setTags(tags);
            _logger.info(toRet.toString());
            //notify mailChimp
            NotificationHandler.notifyAboutUsersNew(user);
            return toRet;
        } else {
            throw new JSONMalFormedException("The mandatory attributes are not in json.", ErrorCodes.JSON_MAL_FORMED);
        }
    }

    public void deleteUser(User user) throws ObjectNotFoundException {
        _logger.info(user.toString());
        String oldMail = getUser(user).getEmail();
        userDao.deleteUser(user.getId());
        //notify mailChimp
        NotificationHandler.notifyAboutUsersDelete(oldMail);
    }

    public void updateUser(String user) throws ObjectNotFoundException {
        _logger.info(user.toString());
        //check if the BasicDBObject is well formed
        FindAndSet fas = ParseJson.getInstance().buildSQLQuery(user, ParseJson.getInstance().getUserFind(), ParseJson.getInstance().getUserUpdate(),
                ParseJson.getInstance().getUserFindStr(), ParseJson.getInstance().getUserUpdateStr());

        //get from json if the name or email is to be modified, if yes, get the current email.
        User mailChimpUser = ParseJson.getInstance().getUserUpdate(user);
        String oldMail = null;
        if (mailChimpUser.getName() != null || mailChimpUser.getEmail() != null) {
            oldMail = getUser(mailChimpUser).getEmail();
        }

        //update the user
        userDao.updateUser(fas);

        //notify mailChimp
        if (oldMail != null) {
            NotificationHandler.notifyAboutUsersUpdate(oldMail, mailChimpUser);
        }


    }

    public User getUser(User user) throws ObjectNotFoundException {

        ResultSet rs = userDao.getUser(user.getId());
        User toRet = new User();
        try {
            if (rs.next()) {
                toRet.setId(user.getId());
                toRet.setName(rs.getString("name"));
                toRet.setEmail(rs.getString("email"));
            }
        } catch (SQLException ex) {
            _logger.error(ex);
        }

        _logger.info(toRet.toString());
        return toRet;
    }

    private String getUserTags(int userId) {
        ResultSet rs = userDao.getUserTags(userId);
        String toRet = "";
        try {
            while (rs.next()) {
                toRet += (rs.getString(1)) + _tagsSeparator;
            }
        } catch (SQLException ex) {
            _logger.error(ex);
        }

        _logger.info(toRet);
        return toRet;
    }

    /**
	 * @author Paulo Fournier
     * Issue: IFL-1565 
	 * Reads int value from SQL result set that might be null
     * @param resultSet
     * @param columnName
     * @return Integer the sql int value (NULL INT)
     */
    private Integer readInteger(ResultSet resultSet, String columnName) {
        Integer ret = null;

        try {
            int val = resultSet.getInt(columnName);
            ret = val;
        } catch (Exception ex) {
        }

        return ret;
    }

    /**
	 * @author Paulo Fournier
     * Issue: IFL-1565
     * Handler to check the user's authentication
     * @param login The user's login
     * @param password The user's password
     * @return User If success, return the user's object
     */
    public com.comut.crud.pojo.mobile.User checkAuthentication(String login, String password) {
        ResultSet resultSet = userDao.checkAuthentication(login, password);
        com.comut.crud.pojo.mobile.User ret = new com.comut.crud.pojo.mobile.User();

        try {
            if (resultSet.next()) {                
                ret.setActivation(resultSet.getDate("activation"));
                ret.setAuthType(readInteger(resultSet, "auth_type"));
                ret.setEmail(resultSet.getString("email"));
                ret.setEmailStatus(readInteger(resultSet, "email_status"));
                ret.setExpiration(resultSet.getDate("expiration"));
                ret.setGroupAlias(resultSet.getString("group_alias"));
                ret.setGroupId(readInteger(resultSet, "group_id"));
                ret.setIdChannel(readInteger(resultSet, "id_channel"));
                ret.setIdLogo(readInteger(resultSet, "id_logo"));
                ret.setRoleAlias(resultSet.getString("role_alias"));
                ret.setRoleId(readInteger(resultSet, "role_id"));
                ret.setSubGroupAlias(resultSet.getString("sub_group_alias"));
                ret.setSubGroupId(readInteger(resultSet, "sub_group_id"));
                ret.setSubGroupIdLogo(readInteger(resultSet, "sub_group_id_logo"));
                ret.setUserId(readInteger(resultSet, "user_id"));
                ret.setUserName(resultSet.getString("user_name"));
            }
        } catch (SQLException ex) {
            _logger.error(ex);
        }

        return ret;
    }
}
